'use client'

import React, { useState, useRef, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { 
  IconUpload, 
  IconDownload, 
  IconFile, 
  IconFileText, 
  IconTable,
  IconCheck,
  IconAlertCircle,
  IconDatabase
} from '@tabler/icons-react'
import { toast } from 'sonner'
import { 
  exportHospitalData, 
  importHospitalData, 
  createFileUploadConfig,
  SupportedFormat,
  ImportResult 
} from '@/lib/dataImportExport'
import { initializeDemoData } from '@/lib/initDemoData'

interface DataManagementPanelProps {
  className?: string
}

export default function DataManagementPanel({ className = '' }: DataManagementPanelProps) {
  const [isImporting, setIsImporting] = useState(false)
  const [isExporting, setIsExporting] = useState(false)
  const [importResult, setImportResult] = useState<ImportResult | null>(null)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [isInitialized, setIsInitialized] = useState(false)
  
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 初始化演示数据
  useEffect(() => {
    const initData = async () => {
      try {
        await initializeDemoData()
        setIsInitialized(true)
      } catch (error) {
        console.error('初始化演示数据失败:', error)
        // 即使失败也设置为已初始化，避免阻塞用户操作
        setIsInitialized(true)
      }
    }
    
    initData()
  }, [])

  // 处理文件选择
  const handleFileSelected = async (file: File) => {
    setSelectedFile(file)
    setImportResult(null)
    
    // 验证文件类型
    const validExtensions = ['.json', '.csv', '.xls', '.xlsx']
    const isValidFile = validExtensions.some(ext => file.name.toLowerCase().endsWith(ext))
    
    if (!isValidFile) {
      toast.error('请选择JSON、CSV或Excel格式的文件')
      return
    }
    
    toast.success(`已选择文件: ${file.name}`)
  }

  // 执行数据导入
  const handleImport = async () => {
    if (!selectedFile) {
      toast.error('请先选择要导入的文件')
      return
    }

    setIsImporting(true)
    
    try {
      const result = await importHospitalData(selectedFile)
      setImportResult(result)
      
      if (result.success) {
        toast.success(`数据导入成功！共导入 ${result.count} 条记录`)
        // 清除选择的文件
        setSelectedFile(null)
        if (fileInputRef.current) {
          fileInputRef.current.value = ''
        }
      } else {
        toast.error(result.error || '数据导入失败')
      }
    } catch (error) {
      toast.error('导入过程中发生错误')
      console.error('导入错误:', error)
    } finally {
      setIsImporting(false)
    }
  }

  // 执行数据导出
  const handleExport = async (format: SupportedFormat) => {
    setIsExporting(true)
    
    try {
      await exportHospitalData(format)
      toast.success(`数据已成功导出为 ${format.toUpperCase()} 格式`)
    } catch (error) {
      toast.error('数据导出失败')
      console.error('导出错误:', error)
    } finally {
      setIsExporting(false)
    }
  }

  // 清除导入结果
  const clearImportResult = () => {
    setImportResult(null)
    setSelectedFile(null)
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  // 文件上传配置
  const fileUploadConfig = createFileUploadConfig(handleFileSelected)

  return (
    <div className={`grid grid-cols-1 lg:grid-cols-2 gap-6 ${className}`}>
      {/* 数据导入面板 */}
      <Card className="border-blue-200 bg-blue-50/30">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-blue-700">
            <IconUpload className="w-5 h-5" />
            数据导入
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 文件选择 */}
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <input
                ref={fileInputRef}
                type="file"
                {...fileUploadConfig}
                className="hidden"
                id="file-upload"
              />
              <label
                htmlFor="file-upload"
                className="flex items-center gap-2 px-4 py-2 border border-blue-300 rounded-lg cursor-pointer hover:bg-blue-100 transition-colors"
              >
                <IconFile className="w-4 h-4" />
                选择文件
              </label>
              
              {selectedFile && (
                <Badge variant="secondary" className="flex items-center gap-1">
                  <IconFileText className="w-3 h-3" />
                  {selectedFile.name}
                </Badge>
              )}
            </div>
            
            <div className="text-sm text-gray-600">
              支持格式：JSON (.json)、CSV (.csv)、Excel (.xls/.xlsx)
            </div>
          </div>

          {/* 导入按钮 */}
          <div className="flex gap-2">
            <Button
              onClick={handleImport}
              disabled={!selectedFile || isImporting}
              className="flex-1 bg-blue-600 hover:bg-blue-700"
            >
              {isImporting ? (
                <>
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
                  导入中...
                </>
              ) : (
                <>
                  <IconUpload className="w-4 h-4 mr-2" />
                  开始导入
                </>
              )}
            </Button>
            
            {(selectedFile || importResult) && (
              <Button
                variant="outline"
                onClick={clearImportResult}
                className="border-blue-300"
              >
                清除
              </Button>
            )}
          </div>

          {/* 导入结果显示 */}
          {importResult && (
            <Alert className={importResult.success ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}>
              <div className="flex items-center gap-2">
                {importResult.success ? (
                  <IconCheck className="w-4 h-4 text-green-600" />
                ) : (
                  <IconAlertCircle className="w-4 h-4 text-red-600" />
                )}
                <AlertDescription className={importResult.success ? 'text-green-700' : 'text-red-700'}>
                  {importResult.success 
                    ? `导入成功！共处理 ${importResult.count} 条记录`
                    : importResult.error
                  }
                </AlertDescription>
              </div>
            </Alert>
          )}
        </CardContent>
      </Card>

      {/* 数据导出面板 */}
      <Card className="border-green-200 bg-green-50/30">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-green-700">
            <IconDownload className="w-5 h-5" />
            数据导出
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="text-sm text-gray-600 mb-4">
            导出当前系统中的所有医院数据，包括医院信息、科室数据和设备清单。
          </div>
          
          {/* 导出格式选择 */}
          <div className="grid grid-cols-1 gap-3">
            <Button
              onClick={() => handleExport('json')}
              disabled={isExporting}
              variant="outline"
              className="justify-start border-green-300 hover:bg-green-100"
            >
              <IconFileText className="w-4 h-4 mr-2" />
              <div className="text-left">
                <div className="font-medium">JSON 格式</div>
                <div className="text-xs text-gray-500">完整数据结构，适合系统间传输</div>
              </div>
            </Button>

            <Button
              onClick={() => handleExport('csv')}
              disabled={isExporting}
              variant="outline"
              className="justify-start border-green-300 hover:bg-green-100"
            >
              <IconTable className="w-4 h-4 mr-2" />
              <div className="text-left">
                <div className="font-medium">CSV 格式</div>
                <div className="text-xs text-gray-500">表格格式，适合Excel处理</div>
              </div>
            </Button>

            <Button
              onClick={() => handleExport('excel')}
              disabled={isExporting}
              variant="outline"
              className="justify-start border-green-300 hover:bg-green-100"
            >
              <IconDatabase className="w-4 h-4 mr-2" />
              <div className="text-left">
                <div className="font-medium">Excel 格式</div>
                <div className="text-xs text-gray-500">电子表格，支持公式和格式</div>
              </div>
            </Button>
          </div>

          {/* 导出状态 */}
          {isExporting && (
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm text-green-600">
                <div className="w-4 h-4 border-2 border-green-600 border-t-transparent rounded-full animate-spin" />
                正在导出数据...
              </div>
              <Progress value={85} className="h-2" />
            </div>
          )}
        </CardContent>
      </Card>

      {/* 使用说明 */}
      <Card className="lg:col-span-2 border-gray-200">
        <CardHeader>
          <CardTitle className="text-gray-700">使用说明</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 text-sm text-gray-600">
            <div>
              <h4 className="font-medium text-gray-800 mb-2">数据导入</h4>
              <ul className="space-y-1">
                <li>• 支持 JSON、CSV 和 Excel 格式文件</li>
                <li>• JSON 文件需包含完整的数据结构</li>
                <li>• CSV 文件需包含标题行，复杂对象以JSON格式存储</li>
                <li>• Excel 文件支持导入我们导出的格式</li>
                <li>• 导入的数据会添加到现有系统中</li>
                <li>• 支持批量导入医院、科室、设备数据</li>
              </ul>
            </div>
            <div>
              <h4 className="font-medium text-gray-800 mb-2">数据导出</h4>
              <ul className="space-y-1">
                <li>• JSON 格式保留完整数据结构</li>
                <li>• CSV 格式适合 Excel 编辑</li>
                <li>• Excel 格式支持公式和样式</li>
                <li>• 导出文件自动添加时间戳</li>
                <li>• 包含所有医院管理相关数据</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}